#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/sysinfo.h>


struct cpu_occupy
{
	char name[20];
	/*
	 *	从系统启动开始累计到当前时刻，用户态的CPU时间（单位：jiffies）,
	 *	不包含 nice值为负进程。1jiffies=0.01秒
	 */
	unsigned int user;		// use time 
	/*
	 *	从系统启动开始累计到当前时刻，nice值为负的进程所占用的CPU时间
	 */	
	unsigned int nice;		// nice time
	/*
	 *	从系统启动开始累计到当前时刻，核心时间
	 */
	unsigned int system;	// syste time
	/*
	 *	从系统启动开始累计到当前时刻，除硬盘IO等待时间以外其它等待时间
	 */
	unsigned int idle;		// idle time
	/*
	 *	从系统启动开始累计到当前时刻，硬盘IO等待时间
	 */
	unsigned int wait;		// waitting time
	/*
	 *	从系统启动开始累计到当前时刻，硬中断时间
	 */
	unsigned int irq;		// hard irq time
	/*
	 *	从系统启动开始累计到当前时刻，软中断时间
	 */
	unsigned int softirq;	// soft irq time
	unsigned int stl;		// steal time
};

static void get_cpuoccupy(struct cpu_occupy * cpu)
{
	FILE *fd;
	int n;
	char buff[256];
	struct cpu_occupy * cpu_tmp;

	cpu_tmp = cpu;

	fd = fopen("/proc/stat", "r");
	fgets(buff, sizeof buff, fd);
	sscanf(buff, "%s %u %u %u %u %u %u %u %u", &cpu_tmp->name, &cpu_tmp->user,
					&cpu_tmp->nice, &cpu_tmp->system, &cpu_tmp->idle,
					&cpu_tmp->wait, &cpu_tmp->irq, &cpu_tmp->softirq,
					&cpu_tmp->stl);
	#if 0
	printf("buff:%s\n", buff);
	printf("name:%s\n", cpu_tmp->name);
	printf("user:%u\n", cpu_tmp->user);
	printf("nice:%u\n", cpu_tmp->nice);
	printf("system:%u\n", cpu_tmp->system);
	printf("idle:%u\n", cpu_tmp->idle);
	printf("wait:%u\n", cpu_tmp->wait);
	printf("irq:%u\n", cpu_tmp->irq);
	printf("softirq:%u\n", cpu_tmp->softirq);
	printf("stl:%u\n", cpu_tmp->stl);
	#endif
	fclose(fd);
}

#define user_time	new->user
#define nice_time	new->nice
#define syst_time	new->system
#define idle_time	new->idle
#define wait_time	new->wait
#define irq_time	new->irq
#define soft_time	new->softirq
#define stl_time	new->stl

int print_cpu_rate()
{
	struct cpu_occupy *new;
	float cpu;
	float us, sy, id, ni, wa, hi, si, st;

	new = (struct cpu_occupy *)malloc(sizeof(struct cpu_occupy));
	get_cpuoccupy(new);
	cpu = (user_time + nice_time + syst_time + idle_time + wait_time
			+ irq_time + soft_time + stl_time) * 1.0;
	
	us = (user_time + nice_time) / cpu * 100.0;
	sy = (syst_time + irq_time + soft_time) / cpu * 100.0;
	id = idle_time / cpu * 100.0;
	ni = nice_time / cpu * 100.0;
	wa = wait_time / cpu * 100.0;
	hi = irq_time  / cpu * 100.0;
	si = soft_time / cpu * 100.0;
	st = stl_time  / cpu * 100.0;

	//printf("cpu:%8.1f\n", cpu);

	printf("%6s%8s%8s%8s%8s%8s%8s%8s%8s\n", "", "us", "sy", "id", "ni", "wa", "hi", "si", "st");

	printf("%6s%8.1f%8.1f%8.1f%8.1f%8.1f%8.1f%8.1f%8.1f\n", "cpu:", us, sy, 
													id, ni, wa, hi, si, st);

	sleep(5);
}

int main()
{
	while(1)
	print_cpu_rate();

	return 0;
}


